package com.woniuxy.sale.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.commons.entity.sale.dto.SoAccountDto;
import com.woniuxy.commons.entity.sale.ChooseProduceMsg;
import com.woniuxy.commons.entity.sale.SoAccount;
import com.woniuxy.commons.entity.sale.vo.sale.SoAccountUpdateVo;
import com.woniuxy.commons.enums.DictCodeEnum;
import com.woniuxy.commons.rabbit.GoldService;
import com.woniuxy.commons.rabbit.RabbitMqConst;
import com.woniuxy.commons.result.Result;
import com.woniuxy.commons.utils.PageUtils;
import com.woniuxy.commons.entity.sale.vo.sale.SoAccountVo;
import com.woniuxy.sale.config.DictConfig;
import com.woniuxy.sale.mapper.ChooseProduceMsgDao;
import com.woniuxy.sale.mapper.SoAccountDao;
import com.woniuxy.sale.service.SoAccountService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO:
 * <P> Date: 2022/4/19:14:24
 * <P> Description:
 */
@Service
public class SoAccountServiceImpl implements SoAccountService {

    @Resource
    private SoAccountDao soAccountDao;

    @Resource
    private ChooseProduceMsgDao chooseProduceMsgDao;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private GoldService goldService;

    @Transactional
    @Override
    public Result add(SoAccount soAccount) {
        soAccount.setSoStatus("1");
        int result = soAccountDao.add(soAccount);

        //TODO 如果插入选货单成功
        if (result > 0) {
            List<ChooseProduceMsg> chooseProduceMsgs = soAccount.getChooseProduceMsgs();

            //TODO 如果当前选货单的选货信息不为空
            if (chooseProduceMsgs != null &&
                    chooseProduceMsgs.size() > 0) {
                //TODO 设置选货单的id
                chooseProduceMsgs.forEach(chooseProduceMsg -> {
                    chooseProduceMsg.setSoId(soAccount.getSoId());
                });
                result = chooseProduceMsgDao.addList(chooseProduceMsgs);

                if (result > 0) {
                    //发送给商品交换机
                    goldService.send(chooseProduceMsgs,
                            RabbitMqConst.EXCHANGE_DIRECT_PRODUCT,
                            RabbitMqConst.ROUTING_PRODUCT);
                    return Result.ok();
                }
            }
        }

        return Result.fail();
    }

    @Override
    public Result findSoAccountAll(Integer currentPage, Integer limit, SoAccountVo soAccountVo) {
        PageHelper.startPage(currentPage, limit);


        List<SoAccount> list = chooseProduceMsgDao.findSoAccountAll(soAccountVo);

        PageInfo<SoAccount> of = PageInfo.of(list);

        //TODO 设置分页信息
        PageUtils pageUtils = new PageUtils(list, (int) of.getTotal(), of.getPageSize(), of.getPageNum());


        //封装数据返回
        ArrayList<SoAccountDto> soAccountDtos = new ArrayList();
        list.stream()
                .map(soAccount -> {
                    SoAccountDto soAccountDto = new SoAccountDto();

                    packSoAccount(soAccount, soAccountDto);

                    soAccountDtos.add(soAccountDto);
                    return null;
                })
                .count();


        //重新设置返回数据
        pageUtils.setList(soAccountDtos);


        return Result.ok(pageUtils);
    }

    @Override
    public Result findSoAccountById(SoAccountVo soAccountVo) {
        List<SoAccount> soAccountAll = chooseProduceMsgDao.findSoAccountAll(soAccountVo);
        if (soAccountAll.size() > 0) {
            SoAccount soAccount = soAccountAll.get(0);
            SoAccountDto soAccountDto = new SoAccountDto();



            ProductServiceImpl.setField(soAccount,soAccountDto, "condition", DictCodeEnum.CONDITION);

            ProductServiceImpl.setField(soAccount,soAccountDto, "regin", DictCodeEnum.REGION);

            ProductServiceImpl.setField(soAccount,soAccountDto, "soType", DictCodeEnum.CATEGORY);



            ProductServiceImpl.setField(soAccount, soAccountDto, "repository",
                    Objects.requireNonNull(DictCodeEnum.getDictCode
                            (Math.toIntExact(DictConfig.getDictOne(DictCodeEnum.REGION.getId(),
                                    Integer.parseInt(soAccount.getRegin())).getId()))));

            ProductServiceImpl.setField(soAccount, soAccountDto, "soStatus",DictCodeEnum.CHOOSE_ORDER_STATUS);
            BeanUtils.copyProperties(soAccount,soAccountDto);

            soAccountDto.setSoOperateStatus(soAccount.getSoOperateStatus() + "");


            return Result.ok(soAccountDto);

        }
        return Result.fail();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateSoAccountStatusById(SoAccountUpdateVo soAccountUpdateVo) {

        int result = soAccountDao.updateSoAccountStatusById(soAccountUpdateVo);
        return result > 0 ? Result.ok().message("修改状态成功") :Result.fail().message("系统繁忙");
    }

    private void  packSoAccount(SoAccount soAccount, SoAccountDto soAccountDto) {
        BeanUtils.copyProperties(soAccount, soAccountDto);

        //TODO 输入对应状态的枚举 返回这个字典对应所有的值
        DictConfig.getDict((long) DictCodeEnum.CHOOSE_ORDER_STATUS.getId()).stream()
                //TODO 过滤器 根据字典对象的value值和本身的值做对比 则返回true
                .filter(dict -> {
                    return dict.getValue().compareTo(Long.valueOf(soAccount.getSoStatus())) == 0;
                })
                //TODO 取得List的第一个下标
                .findFirst()
                //TODO 如果当前对象不为空 那么则设置对应的值
                .ifPresent(dict -> soAccountDto.setSoStatus(dict.getName()));

        DictConfig.getDict((long) DictCodeEnum.CONDITION.getId())
                .stream()
                .filter(dict -> {
                    return dict.getValue().compareTo(Long.valueOf(soAccount.getCondition())) == 0;
                }).findFirst()
                .ifPresent(dict -> soAccountDto.setCondition(dict.getName()));


        ProductServiceImpl.setField(soAccount,soAccountDto,"soType",DictCodeEnum.CATEGORY);

        ProductServiceImpl.setField(soAccount, soAccountDto, "repository",
                Objects.requireNonNull(DictCodeEnum.getDictCode
                        (Math.toIntExact(DictConfig.getDictOne(DictCodeEnum.REGION.getId(),
                                Integer.parseInt(soAccount.getRegin())).getId()))));
    }


}
